<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule;

use Nette\Object;
use \Nette\Environment;
use Nette\Web\IUser;
use Nette\Application\Application;
use Albireo\Mode;

/**
 * SingModel
 *
 * @author Albireo Solutions
 */
class SignModel extends Object {

    /**
     * Signs out the given user. If no parameters are specified, currently signed-in user
     * is used (and signed out).
     *
     * @param \Nette\Web\IUser|null $user
     * @param bool $clearIdentity
     * @return void
     */
    public function signOut(IUser $user = null, $clearIdentity = true) {
        if ($user === null) {
            $user = Environment::getUser();
        }
        return $user->logout($clearIdentity);
        //$redirectPresenter->redirect()
    }

    public function signIn(IUser $user, array $values) {
        if (Mode::isCritical()) {
            $user->setAuthenticationHandler(new KernelMasterAuthenticator());
        }

        //TODO: FILTHY!!! refactor -- ye, it's really filthy
        $app = Environment::getApplication()->getPresenter();

        // Nette changes session token itself (recommended by ISO/IEC 27002)
        $user->login($values['username'], $values['password']);

        if(array_key_exists("redirect", $values) && $values["redirect"] !== false) {
            if (substr($values['redirect'], 0, 1) == ":") {
                $resource = substr($values['redirect'], 1);
            }
            $privilege = substr($resource, strrpos($resource, ":") + 1);
            $resource = substr($resource, 0, strrpos($resource, ":"));
            
            if ($user->isAllowed($resource, $privilege)) {
                $app->redirect($values['redirect']);
            } else {
                //            $this->signOut($user);
                $app->flashMessage(_("You do not have enough rights to sign in to Kernel."));
                $app->redirect(":Kernel:SignIn:");
            }
        }

    }

}